package com.szosen.measurement;

import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.szosen.bluetooth.BluetoothListActivity;
import com.szosen.bluetooth.BluetoothService;
import com.szosen.bluetooth.mBluetoothService;
import com.szosen.database.DBService;
import com.szosen.database.niaoye;
import com.szosen.device.GmpUa;
import com.szosen.device.HealthDevice;
import com.szosen.device.GmpUa.UaRecord;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.util.BackGroundThread;
import com.szosen.util.BackGroundThread.BackGroundTask;
import com.szosen.util.Cache;
import com.szosen.util.ToastTool;

/**
 * 尿液分析仪,可以测量 白细胞 亚硝酸盐 尿胆原 蛋白质 pH值 潜血 比重 酮体 胆红素 葡萄糖 维生素C 12个项目
 * 
 */
public class MeasureUrineBackup extends BaseActivity {

	private static TextView statusView = null;// 蓝牙连接状态
	private static String btName = "EMP-UI";// 蓝牙名称
	private static String btMac = null;// 蓝牙mac
	private static Context context;
	private static Button uploadButton;// 上次数据按钮
	private static Button getDataButton;// 获取最新数据按钮
	private static Button findButton;// 查找设备按钮
	private static EditText leuEditText;
	private static EditText nitEditText;
	private static EditText ubgEditText;
	private static EditText proEditText;
	private static EditText phEditText;
	private static EditText sgEditText;
	private static EditText bldEditText;
	private static EditText ketEditText;
	private static EditText bilEditText;
	private static EditText gluEditText;
	private static EditText vcEditText;
	private static EditText dateEditText;

	private static ImageView imageView1;
	private static ImageView imageView2;
	private static ImageView imageView3;
	private String dataStr;

	private static final String TAG = "MeasureUrine";
	// private static final int UPLOADE_RESULT = 0x10245;
	private static BluetoothService bluetoothService = null;
	OnClickListener clickListener;
	EditText user;
	String username;
	int userid;
	String token;
	private Cache cache;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.measure_urine);
		super.setTitleContent("【尿液测量】");
		context = this;
		token = getIntent().getStringExtra("token");
		findViewid();
		cache = new Cache(context);
		if (token != null)
			uploadButton.setText("获取数据");
		setOnClickListener();// 设置监听器
		setConnectState();
		uploadButton.setEnabled(false);
	}

	public void connnectDeviceAgain(View view) {
		connectGmpUa();
	}

	@Override
	@SuppressLint("ResourceAsColor")
	protected void onResume() {
		super.onResume();
		connectGmpUa();
	}

	/**
	 * 设置监听器
	 */
	private void setOnClickListener() {
		clickListener = new OnClickListener() {
			@Override
			public void onClick(View view) {
				if (view == getDataButton) {
					sendCommd(GmpUa.COMMAND_SINGLE_DATA);
					uploadButton.setEnabled(true);// 获取数据后才能上传数据
				} else if (view == findButton) {
					startDeviceListActivity();// 开启查找蓝牙activity
				} else if (view == uploadButton) {
					uploadAuto();
				}
			}
		};
		uploadButton.setOnClickListener(clickListener);
		getDataButton.setOnClickListener(clickListener);
		findButton.setOnClickListener(clickListener);
	}

	/* 自动上传 */
	private void uploadAuto() {
		// uploadButton.setEnabled(false);// 按钮不可用，避免多次上传
		try {
			upload();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// Toast.makeText(context, "后台开始上传", Toast.LENGTH_SHORT).show();
		if (token != null) {
			Intent intent = getIntent();
			intent.putExtra("data", dataStr);
			setResult(13, intent);
			finish();
		}
	}

	protected void upload() throws JSONException {
		String leu = leuEditText.getText().toString();
		if (TextUtils.isEmpty(leu)) {
			ToastTool.showShort(context, "请先开始测量！");
			return;
		}
		niaoye niaoyeBean = new niaoye();
		niaoyeBean.setIdCard(BaseActivity.getIdCard());
		niaoyeBean.setLeu(leuEditText.getText().toString());
		niaoyeBean.setNit(nitEditText.getText().toString());
		niaoyeBean.setUbg(ubgEditText.getText().toString());
		niaoyeBean.setPro(proEditText.getText().toString());
		niaoyeBean.setPh(phEditText.getText().toString());
		niaoyeBean.setSg(sgEditText.getText().toString());
		niaoyeBean.setBld(bldEditText.getText().toString());
		niaoyeBean.setKet(ketEditText.getText().toString());
		niaoyeBean.setBil(bilEditText.getText().toString());
		niaoyeBean.setGlu(gluEditText.getText().toString());
		niaoyeBean.setVc(vcEditText.getText().toString());
		niaoyeBean.setTime(dateEditText.getText().toString());
		boolean b = DBService.add(niaoyeBean);
		if (b) {
			ToastTool.showLong(context, "数据保存成功");
		} else {
			ToastTool.showLong(context, "数据保存成功");
		}
	}

	/**
	 * 初始化控件
	 */
	private void findViewid() {
		imageView1 = (ImageView) findViewById(R.id.urine_status_image1);
		imageView2 = (ImageView) findViewById(R.id.urine_status_image2);
		imageView3 = (ImageView) findViewById(R.id.urine_status_image3);
		uploadButton = (Button) findViewById(R.id.upload_button);
		getDataButton = (Button) findViewById(R.id.get_data_button);
		leuEditText = (EditText) findViewById(R.id.leu);
		nitEditText = (EditText) findViewById(R.id.nit);
		ubgEditText = (EditText) findViewById(R.id.ubg);
		proEditText = (EditText) findViewById(R.id.pro);
		phEditText = (EditText) findViewById(R.id.pH);
		sgEditText = (EditText) findViewById(R.id.sg);
		bldEditText = (EditText) findViewById(R.id.bld);
		ketEditText = (EditText) findViewById(R.id.ket);
		bilEditText = (EditText) findViewById(R.id.bil);
		gluEditText = (EditText) findViewById(R.id.glu);
		vcEditText = (EditText) findViewById(R.id.vc);
		dateEditText = (EditText) findViewById(R.id.measure_time);
		statusView = (TextView) findViewById(R.id.connect_status);
		findButton = (Button) findViewById(R.id.find_device);
	}

	/**
	 * 设置连接状态
	 */
	private void setConnectState() {
		setVisibility();
		if (bluetoothService == null) {
			statusView.setText(R.string.unconnect);
			statusView.setTextColor(Color.RED);
			return;
		}
		switch (bluetoothService.getState()) {
		case BluetoothService.STATE_CONNECTING:
			statusView.setText(R.string.connecting);
			statusView.setTextColor(Color.BLUE);
			break;
		case BluetoothService.STATE_CONNECTED:
			statusView.setText("已连接" + btName);
			statusView.setTextColor(Color.BLUE);
			break;
		case BluetoothService.STATE_NONE:
			statusView.setText(R.string.unconnect);
			statusView.setTextColor(Color.RED);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		// try {
		// if (bluetoothService.getState() != BluetoothService.STATE_CONNECTED)
		// {
		// bluetoothService.stop();
		// handler = null;
		// }
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
			// 不显示其他内容。
			BluetoothListActivity.setShowNoBondedDevice(false);
			// bluetoothService.close();
		}
		try {
			if (bluetoothService.getState() != BluetoothService.STATE_CONNECTED) {
				bluetoothService.stop();
				handler = null;
			}
			HealthDevice.PersistWriter.isStart = false;
			bluetoothService.stop();
			// persistWriter.stop();
			persistWriter.interrupt();
			handler = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 开启查找蓝牙设备的activity
	 */
	private void startDeviceListActivity() {
		Intent serverIntent = new Intent(this, BluetoothListActivity.class);
		BluetoothListActivity.setHandler(btHandler);
		// 如果已经连接。就不显示未绑定的蓝牙了
		if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
			// 不显示其他内容。
			BluetoothListActivity.setShowNoBondedDevice(false);
		} else {
			// 如果没有已经绑定的，就是为空了。那就绑定其他的了
			String s = cache.getDeviceAddress(Cache.GMPUA);
			if (TextUtils.isEmpty(s)) {
				BluetoothListActivity.setShowNoBondedDevice(true);
			}
		}
		serverIntent.putExtra("tag", "EMP_Ui");
		startActivityForResult(serverIntent,
				BluetoothListActivity.REQUEST_CONNECT_DEVICE);
	}

	private Handler btHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BluetoothListActivity.WHAT_DISCONNECT_BT:
				if (bluetoothService != null) {
					bluetoothService.stop();
				}
				break;

			default:
				break;
			}
		};
	};
	/**
	 * 是否找到设备。？
	 */
	private boolean hasFindDevice = false;
	private HealthDevice.PersistWriter persistWriter;

	/**
	 * 连接尿液分析仪设备
	 */
	private void connectGmpUa() {
		BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		bluetoothService = BluetoothService.getService(handler, false);
		String address = cache.getDeviceAddress(Cache.GMPUA);
		btMac = address;
		BluetoothDevice device = bluetoothService
				.getBondedDeviceByAddress(address);
		if (device != null) {
			bluetoothService.connect(device);// 连接设备
			persistWriter = new HealthDevice.PersistWriter(bluetoothService,
					GmpUa.CONFIRM, 2000);
			HealthDevice.PersistWriter.isStart = true;
			if (!persistWriter.isAlive())
				persistWriter.start();// 持续握手
			hasFindDevice = true;
		} else {
			hasFindDevice = false;
			Toast.makeText(context, "找不到已配对蓝牙设备，请查找其他设备！", Toast.LENGTH_LONG)
					.show();// 没有配对过得设备，启动查找
		}
	}

	/**
	 * 连接搜索到的尿液分析仪设备
	 * 
	 * @param address
	 */
	private void connectGmpUa(String address) {
		bluetoothService = BluetoothService.getService(handler, false);
		btMac = address;
		BluetoothDevice device = bluetoothService
				.getRemoteDeviceByAddress(address);
		bluetoothService.connect(device);
		persistWriter = new HealthDevice.PersistWriter(bluetoothService,
				GmpUa.CONFIRM, 2000);
		HealthDevice.PersistWriter.isStart = true;
		persistWriter.start();// 持续握手
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case BluetoothService.MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothService.STATE_CONNECTED:
					statusView.setText("已连接" + btName + "");
					statusView.setTextColor(Color.BLUE);
					setVisibility();// 设置测量按钮可见
					break;
				case BluetoothService.STATE_CONNECTING:
					statusView.setText(R.string.connecting);
					statusView.setTextColor(Color.BLUE);
					setVisibility();
					break;
				case BluetoothService.STATE_NONE:
					// 设备未连接。
					try {
						System.out.println("尿液执行重连。。。");
						// connectGmpUa();
					} catch (Exception e) {
					}
					statusView.setText(R.string.unconnect);
					statusView.setTextColor(Color.RED);
					setVisibility();
					break;
				}
				break;

			case BluetoothService.MESSAGE_WRITE:
				byte[] writeBuf = (byte[]) msg.obj;
				new String(writeBuf);
				// Toast.makeText(context,
				// writeMessage,
				// Toast.LENGTH_LONG).show();
				break;
			case BluetoothService.MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				Log.i(TAG, "get得到了蓝牙的数据:" + Arrays.toString(readBuf));
				SparseArray<List<byte[]>> map = GmpUa
						.getLegalPatternsFromBuffer(readBuf);
				int dataSize = map.size();
				for (int i = 0; i < dataSize; i++) {
					int token = map.keyAt(i);// 获取token
					List<byte[]> datas = map.get(token);
					switch (token) {
					case GmpUa.TOKEN_SINGLE_DATA:
						GmpUa.UaRecord record = GmpUa.parseRecord(datas
								.get(datas.size() - 1));
						if (null == record) {
							Toast.makeText(context, "无存储数据", Toast.LENGTH_LONG)
									.show();
						} else {
							showRecord(record);// 显示记录
							uploadAuto();
						}
					}
				}
				break;
			case BluetoothService.MESSAGE_TOAST:
				Toast.makeText(context,
						msg.getData().getString(BluetoothService.TOAST),
						Toast.LENGTH_SHORT).show();
				break;
			case BluetoothService.MESSAGE_DEVICE:
				btName = msg.getData().getString(BluetoothService.DEVICE_NAME);
				String address = msg.getData().getString(
						BluetoothService.DEVICE_ADDRESS);
				cache.saveDeviceAddress(Cache.GMPUA, address);// 保存地址,以便下次自带连接
				break;
			case 9:
				ToastTool.showLong(context, "没有网络连接，离线保存");
				break;
			}
		}
	};

	/**
	 * 设置几个button的显示与隐藏
	 * 
	 * @param status
	 */
	private static void setVisibility() {
		int status;
		if (bluetoothService != null
				&& bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
			status = View.VISIBLE;// 连接时设置可见
		} else {
			status = View.INVISIBLE;// 未连接时设置不可见
		}
		getDataButton.setVisibility(status);
	}

	/**
	 * 发送命令
	 * 
	 * @param command
	 */
	private static void sendCommd(byte[] command) {
		Log.i(TAG, "send:" + Arrays.toString(command));
		if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED
				&& command != null)
			bluetoothService.write(command);
	}

	/**
	 * 显示记录
	 * 
	 * @param record
	 */
	public static void showRecord(UaRecord record) {
		leuEditText.setText(record.leu);
		nitEditText.setText(record.nit);
		ubgEditText.setText(record.ubg);
		proEditText.setText(record.pro);
		phEditText.setText(record.ph);
		sgEditText.setText(record.sg);
		bldEditText.setText(record.bld);
		ketEditText.setText(record.ket);
		bilEditText.setText(record.bil);
		gluEditText.setText(record.glu);
		vcEditText.setText(record.vc);
		dateEditText.setText(record.date);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case BluetoothListActivity.REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(
						BluetoothListActivity.EXTRA_DEVICE_ADDRESS);
				leuEditText.setText("");
				nitEditText.setText("");
				ubgEditText.setText("");
				proEditText.setText("");
				phEditText.setText("");
				sgEditText.setText("");
				bldEditText.setText("");
				ketEditText.setText("");
				bilEditText.setText("");
				gluEditText.setText("");
				vcEditText.setText("");
				dateEditText.setText("");
				connectGmpUa(address);
			}
			break;
		}
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			MeasureUrineBackup.this.setResult(RESULT_OK);
			MeasureUrineBackup.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void uploadInBack(final JSONObject data, final String path,
			final ContentValues values) {
		new BackGroundThread(new BackGroundTask() {

			@Override
			public void process() {
			}
		}).start();
	}

}
